<?php

namespace Admin\Mobile\Controllers;

use Helpers\BaseApi;
use Helpers\Tool;
use Helpers\Controller;

class ApiController extends Controller
{

    /**
     * 调用对应方法
     *
     * @param $name
     * @param $params
     * @return mixed|\Phalcon\Http\Response
     *
     * create by ck 20181115
     * modify by ck 20181116    加入httpMethod判断
     */
    public function __call($name, $params)
    {
        $this->view->disable();
        define('API_VER', str_replace('Action', '', $name));

        $module = Tool::getValue($params, 0, '', function ($val) {
            return ucfirst($val);
        });
        $method = Tool::getValue($params, 1, '');
        unset($params[0], $params[1]);
        $params = array_values($params);
        try {
            $className = "\\Admin\\Mobile\\Api\\{$module}";
            $realMethod = $method . ucfirst(strtolower($this->request->getMethod()));
            if (!class_exists($className)) {
                throw new \Exception('暂不支持该方法', 404);
            }
            if (method_exists($className, $realMethod)) {
                return call_user_func_array([new $className(), $realMethod], $params);
            } elseif (method_exists($className, $method)) {
                return call_user_func_array([new $className(), $method], $params);
            } else {
                throw new \Exception('暂不支持该方法', 404);
            }
        } catch (\Exception $e) {
            return (new BaseApi())->returnError(500, '系统异常', $e->getMessage());
        }
    }
}
